{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa0a55ce-5c01-474e-885d-7bab5d5a9e56",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import math\n",
    "\n",
    "def getSin(amp,freq,phase,sampleList):\n",
    "    return amp*np.sin(-2*math.pi*freq*sampleList+phase)\n",
    "def getCos(amp,freq,phase,sampleList):\n",
    "    return amp*np.cos(-2*math.pi*freq*sampleList+phase)\n",
    "# 1. 获得混合波形\n",
    "srate=3000\n",
    "t=np.linspace(0,1,srate)\n",
    "s1=getSin(amp=5, freq=30, phase=0,sampleList=t)    \n",
    "s2=getCos(amp=3, freq=5, phase=0,sampleList=t)  \n",
    "s3=getSin(amp=10, freq=100, phase=0,sampleList=t)\n",
    "s4=getCos(amp=20, freq=120, phase=0,sampleList=t)  \n",
    "m=s1+s2+s3+s4\n",
    "# 2. 获得傅里叶系数\n",
    "fCoefs = np.fft.fft(m,srate)\n",
    "# 3. 获得振幅列表：每一个绕线的重心到原点的距离\n",
    "amp_list=2*np.abs(fCoefs/srate)\n",
    "# 把频率轴从0~1000 转变成 0~499 然后 -500~-1\n",
    "freqs = np.fft.fftfreq(len(amp_list), 1/srate)\n",
    "# 然后把 频率轴 和 数据 都变成 0hz 在中间，向左是负频率，向右是正频率的形式\n",
    "amp_shifted=np.fft.fftshift(amp_list)\n",
    "freq_shift=np.fft.fftshift(freqs)\n",
    "amp_shifted_copy = np.copy(amp_shifted)#获取图像\n",
    "amp_shifted_copy[amp_shifted < 0.5] = 0#使用掩模\n",
    "amp_shifted_copy[(freq_shift >= 110) | (freq_shift <= -110)] = 0\n",
    "#逆傅里叶变化\n",
    "amp_shifted_ishift=np.fft.ifftshift(amp_shifted_copy)\n",
    "amp_shifted3 = amp_shifted_ishift * srate / 2\n",
    "amp_shifted_ifft=np.fft.ifft(amp_shifted3)\n",
    "# 把振幅列表画出来\n",
    "fig,ax=plt.subplots(2,2,figsize=(16,4))\n",
    "#左上角子图\n",
    "ax[0][0].plot(m)\n",
    "ax[0][0].grid()\n",
    "ax[0][0].set_xlim([0,500])\n",
    "#右上角子图\n",
    "ax[0][1].plot(np.real(amp_shifted_ifft))\n",
    "ax[0][1].grid()\n",
    "ax[0][1].set_xlim([0,500])\n",
    "ax[0][1].set_ylim([-20,20])\n",
    "#左下角子图\n",
    "ax[1][0].stem(freq_shift,amp_shifted)\n",
    "ax[1][0].grid()\n",
    "ax[1][0].set_xlim([-150,150])\n",
    "#右下角子图\n",
    "ax[1][1].stem(freq_shift,amp_shifted_copy)\n",
    "ax[1][1].set_xlim([-150,150])\n",
    "ax[1][1].set_ylim([0, 20])\n",
    "ax[1][1].grid()\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fd59a92-8af1-4c66-adae-72f96c0445b8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
